package com.xhwl.centiotdata.handler.visitor.impl;

import com.alibaba.fastjson.JSONObject;
//import com.swetake.util.Qrcode;
import com.xhwl.centiotdata.handler.visitor.VisitorIntegrationFactory;
import com.xhwl.centiotdata.handler.visitor.VisitorIntegrationHandler;
import com.xhwl.centiotdata.pojo.dto.lifang.DeviceLiFangDTO;
import com.xhwl.centiotdata.pojo.dto.lifang.UserLiFangDTO;
import com.xhwl.centiotdata.pojo.dto.pedestrian.PedestrianIntegrationConfigDTO;
import com.xhwl.centiotdata.pojo.dto.visitor.VisitorIntegrationConfigDTO;
import com.xhwl.centiotdata.service.cent.IDeviceCentService;
import com.xhwl.centiotdata.service.integrateconfig.IntegrationConfig;
import com.xhwl.centiotdata.suppliersystem.lifang.PedestrianLiFangHandler;
import com.xhwl.centiotdata.utils.RedisUtils;
import com.xhwl.common.dto.auth.PedestrianAuthDTO;
import com.xhwl.common.dto.cent.device.DeviceDTO;
import com.xhwl.common.dto.cent.pedes.DeviceAttributeDTO;
import com.xhwl.common.dto.cent.visitor.VisitorAuthDTO;
import com.xhwl.common.enums.CategoryEnum;
import com.xhwl.common.enums.ProductEnum;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.device.DeviceProjSupplierCategory;
import com.xhwl.starter.obs.IObsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
@Service
@Slf4j
public class VisitorIntegrationLiFangHandler extends VisitorIntegrationHandler {
    @Autowired
    private PedestrianLiFangHandler pedestrianLiFangHandler;
    @Autowired
    RedisUtils redisUtils;
    @Autowired
    private IDeviceCentService deviceCentService;
    @Autowired
    IObsService obsService;

    @Override
    public void afterPropertiesSet() throws Exception {
        VisitorIntegrationFactory.register(ProductEnum.LIFANG_OCS.getId(),this);
    }

    @Override
    public ResultJson createVisitorAuth(VisitorIntegrationConfigDTO configDTO, VisitorAuthDTO visitorAuthDTO) {
        //从集成配置获取部门
        List<DeviceProjSupplierCategory> configDTOList = IntegrationConfig.integrationConfigList.stream()
                .filter(configDTO2 -> configDTO.getProjectId().equals(configDTO2.getProjectId()) && CategoryEnum.DOOR.getId().equals(configDTO2.getProdCategoryId()))
                .collect(Collectors.toList());
        Integer depart = configDTOList.get(0).getProperties().getInteger("visitorDepartId");
        UserLiFangDTO userLiFangDTO = UserLiFangDTO.builder()
                .name(visitorAuthDTO.getName())
                .deptId(depart)
                .userType("A")
                .phone(visitorAuthDTO.getPhone())
                .build();
        PedestrianIntegrationConfigDTO configDTO1 = new PedestrianIntegrationConfigDTO();
        BeanUtils.copyProperties(configDTO,configDTO1);
        //创建人员
        String openId = pedestrianLiFangHandler.createUser(configDTO1,userLiFangDTO);
        PedestrianAuthDTO pedestrianAuthDTO = new PedestrianAuthDTO();
        pedestrianAuthDTO.setUserOpenId(openId);
        pedestrianAuthDTO.setCardNumber(createCard());
        pedestrianAuthDTO.setValidStartTime(visitorAuthDTO.getAuthStartTime());
        pedestrianAuthDTO.setValidEndTime(visitorAuthDTO.getAuthEndTime());
        //发卡
        pedestrianLiFangHandler.sendCard(configDTO1,pedestrianAuthDTO);
        //授权
        pedestrianAuthDTO.setAddedThirdDeviceIdList(visitorAuthDTO.getOpenDeviceIdList());
        pedestrianLiFangHandler.createAuth(configDTO1,pedestrianAuthDTO);
        //长期二维码
        long validTime = this.validTime(pedestrianAuthDTO);
        pedestrianAuthDTO.setValidTime(validTime);
        ResultJson resultJson = pedestrianLiFangHandler.getQrCode(configDTO1,pedestrianAuthDTO);
        redisUtils.setWithSeconds("visitor"+visitorAuthDTO.getId().toString(),resultJson.getMessage(),(int)validTime);
        return ResultJson.success();
    }

    @Override
    public ResultJson getQrCode(VisitorIntegrationConfigDTO configDTO, VisitorAuthDTO visitorAuthDTO) {
        String content = redisUtils.get("visitor"+visitorAuthDTO.getId().toString()).toString();
        String url = qRCodeCommon(content,7);
        log.info("QrCodeUrl:{}",url);
        return ResultJson.success(url);
    }

    @Override
    public ResultJson pullPrivilegeGroup(VisitorIntegrationConfigDTO configDTO) {
//        visitorLiFangHandler.pullVisitorDevice(configDTO);
        return ResultJson.success();
    }

        private List<DeviceDTO> handleDevice(VisitorIntegrationConfigDTO configDTO,List<DeviceLiFangDTO> deviceLiFangDTOList ){
        return deviceLiFangDTOList.stream().map(deviceLiFangDTO -> {
            DeviceDTO deviceDTO = new DeviceDTO();
            deviceDTO.setProjectId(configDTO.getProjectId());
            deviceDTO.setProductId(configDTO.getProductId());
            deviceDTO.setCategoryId(CategoryEnum.DOOR.getId());
            deviceDTO.setName(deviceLiFangDTO.getStationName());
            deviceDTO.setThirdDeviceId(deviceLiFangDTO.getStationNo());
            deviceDTO.setType(deviceLiFangDTO.getStationType());
            JSONObject attributeJson = null;
            DeviceAttributeDTO deviceAttributeDTO = new DeviceAttributeDTO();
            deviceAttributeDTO.setIp(deviceLiFangDTO.getStationIp());
            deviceAttributeDTO.setPort(deviceLiFangDTO.getPort().toString());
            attributeJson = (JSONObject) JSONObject.toJSON(deviceAttributeDTO);
            deviceDTO.setAttributeJson(attributeJson);
            return deviceDTO;
        }).collect(Collectors.toList());
    }
    private byte[] handleQrCode(String qr) {
        String hexString = qr.toLowerCase();
        final byte[] byteArray = new byte[hexString.length() / 2];
        int k = 0;
        for (int i = 0; i < byteArray.length; i++) {
            // 转换成字节需要两个16进制的字符，高位在先
            // 将hex 转换成byte   "&" 操作为了防止负数的自动扩展
            // hex转换成byte 其实只占用了4位，然后把高位进行右移四位
            // 然后“|”操作  低四位 就能得到 两个 16进制数转换成一个byte.
            byte high = (byte) (Character.digit(hexString.charAt(k), 16) & 0xff);
            byte low = (byte) (Character.digit(hexString.charAt(k + 1), 16) & 0xff);
            byteArray[i] = (byte) (high << 4 | low);
            k += 2;
        }
        return byteArray;
    }

    private String qRCodeCommon(String content,int size) {
        BufferedImage bufImg = null;
        String url = null;
//        try {
//            Qrcode qrcodeHandler = new Qrcode();
//            // 设置二维码排错率，可选L(7%)、M(15%)、Q(25%)、H(30%)，排错率越高可存储的信息越少，但对二维码清晰度的要求越小
//            qrcodeHandler.setQrcodeErrorCorrect('M');
//            qrcodeHandler.setQrcodeEncodeMode('B');
//            // 设置设置二维码尺寸，取值范围1-40，值越大尺寸越大，可存储的信息越大
//            qrcodeHandler.setQrcodeVersion(size);
//            // 获得内容的字节数组，设置编码格式
//            byte[] contentBytes = handleQrCode(content);
//            // 图片尺寸
//            int imgSize = 67 + 12 * (size - 1);
//            bufImg = new BufferedImage(imgSize, imgSize, BufferedImage.TYPE_INT_RGB);
//            Graphics2D gs = bufImg.createGraphics();
//            // 设置背景颜色
//            gs.setBackground(Color.WHITE);
//            gs.clearRect(0, 0, imgSize, imgSize);
//
//            // 设定图像颜色> BLACK
//            gs.setColor(Color.BLACK);
//            // 设置偏移量，不设置可能导致解析出错
//            int pixoff = 2;
//            // 输出内容> 二维码
//            if (contentBytes.length > 0 && contentBytes.length < 800) {
//                boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes);
//                for (int i = 0; i < codeOut.length; i++) {
//                    for (int j = 0; j < codeOut.length; j++) {
//                        if (codeOut[j][i]) {
//                            gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
//                        }
//                    }
//                }
//            } else {
//                throw new Exception("QRCode content bytes length = " + contentBytes.length + " not in [0, 800].");
//            }
//            gs.dispose();
//            bufImg.flush();
//            ByteArrayOutputStream os = new ByteArrayOutputStream();
//            //将图片写出到指定位置（复制图片）
//            ImageIO.write(bufImg, "png", os);
//            InputStream inputStream = new ByteArrayInputStream(os.toByteArray());
//            url = obsService.uploadImg(inputStream);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        return url;
    }

    private String createCard(){
        int machineId = 2;
        int hashCodeV = UUID.randomUUID().toString().hashCode();
        if(hashCodeV < 0) {
            hashCodeV = - hashCodeV;
        }
        return machineId + String.format("%015d",hashCodeV);
    }

    private long validTime(PedestrianAuthDTO pedestrianAuthDTO){
        long valid = Math.abs(pedestrianAuthDTO.getValidEndTime().getTime()-pedestrianAuthDTO.getValidStartTime().getTime());
        long validtime = TimeUnit.SECONDS.convert(valid,TimeUnit.MILLISECONDS);
        return validtime;
    }
}
